<?php
include($_SERVER["DOCUMENT_ROOT"] . "/bob.php");
include($_SERVER["DOCUMENT_ROOT"] . "/fonctions_globales.php");
include("fonctions_messagerie.php");
$mysqli = new_mysqli($host, $user, $password, $database); //connection à la DB
$variable_post = filter_input_array(INPUT_POST);
if (empty($_SESSION['login'])) {
    header("Location: /");
    exit();
}

$boite = get_alphanum(@$_GET['boite']);
if ($boite == "") {
    $boite = "reception";
}
if (isset($variable_post['btn_archive']) && $variable_post['btn_archive'] == "Archiver") {
    if (isset($variable_post['action_msg'])) {
        for ($i = 0; $i < sizeof($variable_post['action_msg']); $i++) {
            $choix = get_num($variable_post['action_msg'][$i]);
            archiver_message($mysqli, $choix);
        }
    }
} elseif (isset($variable_post['btn_supprimer']) && $variable_post['btn_supprimer'] == "Supprimer") {
    if (isset($variable_post['action_msg'])) {

        for ($i = 0; $i < sizeof($variable_post['action_msg']); $i++) {

            //on met le statut à DELETED pour l'utilisateur connecté  
            $choix = get_num($variable_post['action_msg'][$i]);
            supprimer_message($mysqli, $choix);
        }
    }
}




//Pagination - Initialisation


$nb_message_par_page = 30;
$retour_total = mysqli_query_with_error($mysqli, "SELECT * FROM news ORDER BY date DESC");

$total = $retour_total->num_rows;

$nombreDePages = ceil($total / $nb_message_par_page);
if (isset($variable_get['page'])) {
    if ($variable_get['page'] == 'derniere') {
        $page = $nombreDePages;
    } else {
        $page = $variable_get['page'];
    }
} else {
    $page = 1;
}

$pageActuelle = intval($page);
if ($pageActuelle > $nombreDePages) {
    $pageActuelle = $nombreDePages;
}
$premiereEntree = ($pageActuelle - 1) * $nb_message_par_page;


if ($boite == "envoi") { //recherche des messages concernés
    //$query = "SELECT t.privmsgs_thread_id as id_thread, t.thread_subject as sujet,MAX(m.privmsgs_date) as m_date, m.privmsgs_from_userid as user_from, MAX(m.status_dest) as etat FROM privmsgs as m LEFT JOIN privmsgs_thread as t ON m.thread_id=t.privmsgs_thread_id WHERE m.privmsgs_from_userid=" . $_SESSION['id'] . "  GROUP BY id_thread HAVING MIN(m.status_exp)!='ARCHIVE' AND MIN(m.status_exp)!='DELETED' ORDER BY m.privmsgs_date DESC";
    $query = "SELECT t.privmsgs_thread_id as id_thread, t.thread_subject as sujet, t.privmsgs_thread_update_date as m_date, (SELECT privmsgs_to_userid FROM privmsgs as m WHERE m.thread_id=t.privmsgs_thread_id AND privmsgs_to_userid!=" . $_SESSION['id'] . " ORDER BY privmsgs_id DESC LIMIT 0,1) as user_from, ptg.status_envoi as etat FROM privmsgs_thread as t LEFT JOIN privmsgs_thread_gens as ptg ON t.privmsgs_thread_id=ptg.thread_id WHERE ptg.status_envoi IS NOT NULL AND ptg.user_id=" . $_SESSION['id'] . "  AND ptg.status_envoi!='ARCHIVE' AND ptg.status_envoi!='DELETED' ORDER BY t.privmsgs_thread_update_date DESC";
    //echo $query;
    $value_input_boite = "envoi";
} else if ($boite == "archive") {
    //$query = "SELECT t.privmsgs_thread_id as id_thread, t.thread_subject as sujet,MAX(m.privmsgs_date) as m_date, m.privmsgs_from_userid as user_from, MAX(m.status_dest) as etat FROM privmsgs as m LEFT JOIN privmsgs_thread as t ON m.thread_id=t.privmsgs_thread_id WHERE m.privmsgs_from_userid=" . $_SESSION['id'] . " OR m.privmsgs_to_userid=" . $_SESSION['id'] . "  GROUP BY id_thread HAVING MIN(CASE WHEN m.privmsgs_to_userid =" . $_SESSION['id'] . " THEN m.status_dest ELSE m.status_exp END)='ARCHIVE' ORDER BY m.privmsgs_date DESC";    
    $query = "SELECT t.privmsgs_thread_id as id_thread, t.thread_subject as sujet, t.privmsgs_thread_update_date as m_date, (SELECT (CASE WHEN privmsgs_from_userid=" . $_SESSION['id'] . " THEN privmsgs_to_userid ELSE privmsgs_from_userid END) FROM privmsgs as m WHERE m.thread_id=t.privmsgs_thread_id ORDER BY privmsgs_id DESC LIMIT 0,1) as user_from, ptg.status_recept as etat FROM privmsgs_thread as t LEFT JOIN privmsgs_thread_gens as ptg ON t.privmsgs_thread_id=ptg.thread_id WHERE ptg.user_id=" . $_SESSION['id'] . "  AND ptg.status_recept='ARCHIVE' ORDER BY t.privmsgs_thread_update_date DESC";
    //echo $query;
    $value_input_boite = "archive";
} else {

    $query = "SELECT t.privmsgs_thread_id as id_thread, t.thread_subject as sujet, t.privmsgs_thread_update_date as m_date, (SELECT privmsgs_from_userid FROM privmsgs as m WHERE m.thread_id=t.privmsgs_thread_id AND privmsgs_from_userid!=" . $_SESSION['id'] . " ORDER BY privmsgs_id DESC LIMIT 0,1) as user_from, ptg.status_recept as etat FROM privmsgs_thread as t LEFT JOIN privmsgs_thread_gens as ptg ON t.privmsgs_thread_id=ptg.thread_id WHERE ptg.status_recept IS NOT NULL AND ptg.user_id=" . $_SESSION['id'] . "  AND ptg.status_recept!='ARCHIVE' AND ptg.status_recept!='DELETED' ORDER BY t.privmsgs_thread_update_date DESC";

    $value_input_boite = "reception";
}
$query.=" LIMIT " . $premiereEntree . ', ' . $nb_message_par_page;

$result = mysqli_query_with_error($mysqli, $query);
?>

<?php
main_body($mysqli, "Messagerie", "bandeau;messagerie;forum");
display_bandeau_profil($mysqli, "message");
?>
<script>
    function check_Box()
    {
        $('#btn_archive').blur();
        $('#btn_supprimer').blur();
        var i = 0;
        var COCHE = false;

        for (i = 0; i < document.getElementsByName('action_msg[]').length; i++)
        {
            //alert(i);
            if (document.getElementsByName('action_msg[]').item(i).checked)
            {
                COCHE = true;
                break;
            }
        }

        if (COCHE) {
            return true;
        } else {
            alert("Sélectionnez un message pour l'archiver ou le supprimer");
            return false;
        }
        

    }
</script>
<div id='background_corps'> </div><!-- Div contenant simplement la couleur du corps, qui vient se glisser sous le motif de bulle
                                                                                        (le vrai corp se glisse au-dessus, pour être cliquable). -->
<div id='corps'>
    <div id="contenus">
        <form action="messages.php?boite=<?php echo $boite ?>" method="post" onsubmit="return check_Box()">
            <input type="hidden" name="boite" value="<?php echo $value_input_boite ?>" />
            <ul class="menu-messagerie">
                <li class="btn ombre"><a href="postmess.php">Nouveau message</a></li>
                <li class="bordure"><a href="messages.php" <?php
                    if ($boite == "reception") {
                        echo 'class="current"';
                    }
                    ?>>Boite de réception<?php
                                           $resultg = mysqli_query_with_error($mysqli, "SELECT COUNT(*) as nb FROM privmsgs_thread_gens WHERE user_id='{$_SESSION['id']}' AND status_recept='UNREAD'")->fetch_array();
                                           if ($resultg['nb'] > 0) {
                                               echo " (" . $resultg['nb'] . ")";
                                           }
                                           ?></a></li>
                <li class="bordure"><a href="messages.php?boite=envoi" <?php
                    if ($boite == "envoi") {
                        echo 'class="current"';
                    }
                    ?>>Messages envoyés</a></li>                
                <li><a href="messages.php?boite=archive" <?php
                    if ($boite == "archive") {
                        echo 'class="current"';
                    }
                    ?>>Messages archivés</a></li>
                <span id="action_msg">

                    <li class="btn ombre margin">
                        <?php if ($boite != "archive") { ?>
                            <input type="submit" name="btn_archive" id="btn_archive" value="Archiver"/></li>
                        <li class="btn ombre">
                        <?php } ?>
                        <input type="submit" name="btn_supprimer" id="btn_supprimer" value="Supprimer"/></li>
                </span>
            </ul>
            <div class="messagerie ombre">

                <?php
                if ($result->num_rows == 0) {
                    echo '<p class="vide">Aucun message.</p>';
                } else {

                    if ($boite == "envoi") {
                        $troico = "Destinataire";
                        $deuco = "user_from";
                    } else {
                        $troico = "De";
                        $deuco = "user_from";
                    }

                    $nb_current = 0;
                    while ($ligne = $result->fetch_assoc()) { //affichage du tableau
                        if ($ligne['etat'] == "UNREAD") {
                            echo '<div class="ligne nonlu bordure">';
                        } else {
                            echo '<div class="ligne lu bordure">';
                        }
                        echo '<div class="pseudo"><a href="imessage.php?id=' . $ligne['id_thread'] . '">' . get_data_in_db($mysqli, "gens", "user_id", $ligne[$deuco], "username") . '</a></div>';
                        $sujet = get_data_propre_sortie_db($ligne['sujet']);
                        echo '<div class="titre"><a href="imessage.php?id=' . $ligne['id_thread'] . '">' . $sujet . '</a></div>';
                        echo '<div class="date">' . datouille($ligne['m_date'], true) . '</div>';
                        echo '<div class="box">';
                        //echo '<form action="">';
                        echo '<input class="select_msg" id="select_msg' . $ligne['id_thread'] . '" type="checkbox" name="action_msg[]" value="' . $ligne['id_thread'] . '" /><label for="select_msg' . $ligne['id_thread'] . '"></label>';
                        //echo '</form>';
                        echo "</div>";
                        echo "</div>";
                    }
                }
                ?>
            </div>

            <?php
            pagination_bas('message.php?boite=' . $boite . '&', 'page=', $nombreDePages, $page);
            ?>
        </form>
    </div> <!-- fin div contenu-->
</div> <!-- fin div corps-->

<?php
show_footer();
?>
